<?php

namespace app\admin\controller;

use think\Request;
use app\common\controller\Base;
use app\common\service\Product as ProductService;
use app\common\service\ProductCat as ProductCatService;

class Product extends Base{

    public function index(){

        $productService = new ProductService();

        $products = $productService -> paginate();

        return view('',['products'=>$products]);
    }

    public function add(){

        $productCatService = new ProductCatService();
        $tree = $productCatService -> getMenusTree();

        return view('',['tree'=>$tree]);
    }

    public function edit(Request $request){

        $id = $request->param('id');
        $productService = new ProductService();
        $product = $productService->find($id);

        $productCatService = new ProductCatService();
        $tree = $productCatService -> getMenusTree();


        return view('',['product'=>$product,'tree'=>$tree]);
    }

    public function create(Request $request){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }

        $data = $request->only(['name','cat','cover','price','desc','content']);

        $productService = new ProductService();
        $result = $productService ->insert($data);

        if($result['state']) {
            $this->success("操作成功");
        }else{
            $this->error($result['message']);
        }

    }

    public function update(Request $request){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }

        $data = $request->only(['id','name','cat','cover','price','desc','content']);

        $productService = new ProductService();
        $result = $productService ->update($data);

        if(1 == $result['state']) {
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }

    public function delete(Request $request){
        if(!$request->isDelete()){
            $this->error("非法访问途径");
        }
        $id = $request->param('id');
        if(!intval($id)){
            $this->error("操作错误");
        }

        $productService = new ProductService();
        $result = $productService ->delete($id);

        if($result){
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }

}